package cn.code4java.springbok.service;

import cn.code4java.springbok.dto.ItemSaleChannelDTO;
import cn.code4java.springbok.dto.ItemSaleChannelQueryDTO;
import cn.code4java.springbok.entity.ItemSale;
import cn.code4java.springbok.entity.ItemSaleChannel;
import cn.code4java.springbok.mapper.ItemSaleChannelMapper;
import cn.code4java.springbok.mapper.ItemSaleMapper;
import cn.code4java.springbok.vo.ItemSaleChannelVO;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName ItemSaleChannelServiceImpl
 * @Description: 渠道商品服务实现类
 * @Author xiehuangbao
 * @Date 2024/6/17
 * @Version V2.0.0
 **/
@Slf4j
@Service
@AllArgsConstructor
public class ItemSaleChannelServiceImpl extends BaseServiceImpl<ItemSaleChannelMapper, ItemSaleChannel> implements ItemSaleChannelService {

    private final ItemSaleMapper itemSaleMapper;

    @Override
    public Page<ItemSaleChannelVO> pageItemSaleChannel(ItemSaleChannelQueryDTO itemSaleChannelQueryDTO) {
        return this.baseMapper.pageItemSaleChannel(getPage(), itemSaleChannelQueryDTO);
    }

    @Override
    @Transactional
    public int addItemSaleChannel(ItemSaleChannelDTO itemSaleChannelDTO) {
        itemSaleChannelDTO.getSaleChannels().stream().forEach(saleChannel -> {
            itemSaleChannelDTO.getSysBranchIds().stream().forEach(sysBranchId -> {
                itemSaleChannelDTO.getItemSaleIds().stream().forEach(itemSaleId -> {
                    int count = this.count(Wrappers.<ItemSaleChannel>lambdaQuery()
                            .eq(ItemSaleChannel::getSaleChannel, saleChannel)
                            .eq(ItemSaleChannel::getSysBranchId, sysBranchId)
                            .eq(ItemSaleChannel::getItemSaleId, itemSaleId));
                    if (count == 0) {
                        ItemSale itemSale = itemSaleMapper.selectById(itemSaleId);
                        ItemSaleChannel itemSaleChannel = new ItemSaleChannel();
                        itemSaleChannel.setSaleChannel(saleChannel);
                        itemSaleChannel.setSysBranchId(sysBranchId);
                        itemSaleChannel.setItemSaleChannelName(itemSale.getItemSaleName());
                        itemSaleChannel.setItemSaleId(itemSaleId);
                        itemSaleChannel.setStatus(1);
                        this.save(itemSaleChannel);
                    }
                });
            });
        });
        return 0;
    }
}
